<?php

namespace application\depend;
require_once APP_START_ROOT_PATH.'/vendor/predis/autoload.php';


use Predis\Client;

class PhpRedis{
    static protected $handler = null;
    static protected $options = [
        'cluster' => 'redis',
      //  'parameters' => ['password' => REDIS_CLUSTER_PASS],
    ];
    
        /**
     * 选择缓存所在服务器
     * @access public
     * @param string $name 缓存变量名
     * @param integer $length 截取长度
     * @return boolean
     */
    static private function selectServer($name = ""){
        !empty(REDIS_CLUSTER_PASS) && self::$options['parameters']['password'] = REDIS_CLUSTER_PASS;
        try {
            self::$handler == null && self::$handler = new Client(REDIS_CLUSTER_CACHE, self::$options);
            if(self::$handler == null){
                return false;
            }
            return true;
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => 'ws连接缓存出错',
                'catch-e' => $e->getMessage(),
            ],__FILE__,__LINE__);
            return false;
        }
    }//end function

    /**
     * 读取缓存
     * @access public
     * @param string $name 缓存变量名
     * @return mixed
     */
    static public function get($name){
        if(!self::selectServer($name)) return false;
        $value = self::$handler->get($name);
        $jsonData = json_decode($value, true);
        return ($jsonData === null) ? $value : $jsonData;
    }
    
    /**
     * 写入缓存
     * @access public
     * @param string $name 缓存变量名
     * @param mixed $value 存储数据
     * @param integer $expire 有效时间（秒）
     * @return boolean
     */
    static public function set($name, $value, $expire = null){
        if(!self::selectServer($name)) return false;
        
        //对数组/对象数据进行缓存处理，保证数据完整性
        $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
        if(is_int($expire)){
            $result = self::$handler->setex($name, $expire, $value);
        }else{
            $result = self::$handler->set($name, $value);
        }
        return $result;
    }
    
    /**
     * 删除缓存
     * @access public
     * @param string $name 缓存变量名
     * @return boolean
     */
    static public function rm($name){
        if(!self::selectServer($name)) return false;
        return self::$handler->del($name);
    }
    
    /**
     * 清除缓存
     * @access public
     * @return boolean
     */
    static public function clear(){
        if(!extension_loaded('redis')){
            Applog::appLog('error', ['错误描述' => '未检测到redis扩展'],__FILE__,__LINE__);
            return false;
        }
        if(!self::selectServer()) return true;
        self::$handler->flushdb();
        return true;
    }
    
    /**
     * 列表头（左边）添加值
     */
    static public function lPush($name, $value){
        if(!self::selectServer($name)) return false;
        //对数组/对象数据进行缓存处理，保证数据完整性
        $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
        
        return self::$handler->lPush($name, $value);
    }

    /**
     * @param $name
     * 返回名称的所有值
     */
    static public function lrange($name,$num = -1){
        if(!self::selectServer($name)) return false;
        try {
            return self::$handler->lrange($name, 0, $num);
        }catch(\Exception $e){
            Applog::appLog('error',[
               'info' => '获取缓存队列值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ],__FILE__,__LINE__);
            return false;
        }
    }//end


    /**
     * 列表尾（右边）添加值
     */
    static public function rPush($name, $value){
        if(!self::selectServer($name)) return false;
        //对数组/对象数据进行缓存处理，保证数据完整性
        $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
        try {
            return self::$handler->rPush($name, $value);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => '添加缓存队列值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ],__FILE__,__LINE__);
            return false;
        }
    }
    
    /**
     * 输出并删除列表头（左）第一个元素
     */
    static public function lPop($name){
        if(!self::selectServer($name)) return false;
        try {
            return self::$handler->lPop($name);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => '添加缓存队列值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ],__FILE__,__LINE__);
            return false;
        }//end try catch
    }
    
    /**
     * 输出并删除列表尾（右）第一个元素
     */
    static public function rPop($name){
        if(!self::selectServer($name)) return false;
        try {
            return self::$handler->rPop($name);
        }catch (\Exception $e){
            Applog::appLog('error',[
                'info' => '添加缓存队列值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ],__FILE__,__LINE__);
            return false;
        }
    }
    
    /**
     * 删除$count个名称为$name的列表中值为$value的元素
     * $count为0，删除所有值为$value的元素，
     * $count>0从头至尾删除$count个值为$value的元素
     * $count<0从尾到头删除|$count|个值为$value的元素
     */
    static public function lRem($name, $value, $count = 0){
        if(!self::selectServer($name)) return false;
        //对数组/对象数据进行缓存处理，保证数据完整性
        $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
        $count = intval($count);
        try {
            return self::$handler->lRem($name, $value, $count);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => '添加缓存队列值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }
    
    /**
     * 向名称为h的hash中添加元素key->value
     */
    static public function hSet($h, $key, $value){
        if(!self::selectServer($h)) return false;
        $key = strval($key);
        $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
        try {
            return self::$handler->hSet($h, $key, $value);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => '添加缓存队列值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }
    
    /**
     * 返回名称为h的hash中key对应的value
     */
    static public function hGet($h, $key){
        if(!self::selectServer($h)) return false;
        $key = strval($key);
        try {
            return self::$handler->hGet($h, $key);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => '添加缓存队列值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }
    
    /**
     * 返回名称为h的hash中元素个数
     */
    static public function hLen($h){
        if(!self::selectServer($h)) return false;
        try {
            return self::$handler->hLen($h);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => '添加缓存队列值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }//end
    }
    
    /**
     * 删除名称为h的hash中键为key的域
     */
    static public function hDel($h, $key){
        if(!self::selectServer($h)) return false;
        if(!is_array($key)){
            $key = (array)$key;
        }
        try {
            return self::$handler->hdel($h, $key);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => '删除缓存队列值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }

    /**
     * @param $h
     * @param $key
     */
    static public function hexists($h,$key){
        if(!self::selectServer($h)) return false;
        try{
            return self::$handler->hexists($h,$key);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => '查询hash值是否存在出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }

    /**
     * 返回名称为h的hash中所有键（key）
     */
    static public function hKeys($h){
        if(!self::selectServer($h)) return false;
        try {
            return self::$handler->hkeys($h);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => '删除缓存队列值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }
    
    /**
     * 返回名称为h的hash中所有键对应的值（value）
     */
    static public function hVals($h){
        if(!self::selectServer($h)) return false;
        try {
            return self::$handler->hvals($h);
        }catch(\Exception $e){

            Applog::appLog('error',[
                'info' => '获取缓存hash值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }
    
    /**
     * 返回名称为h的hash中所有的键（key）及其对应的值（value）
     */
    static public function hGetAll($h){
        if(!self::selectServer($h)) return false;
        try {
            return self::$handler->hGetAll($h);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'info' => '删除缓存所有hash 的键值出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }
    
    /**
     * 向名称为h的hash中批量添加元素
     */
    static public function hMset($h, $arr){
        if(!self::selectServer($h)) return false;
        try {
            return self::$handler->hMset($h, $arr);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'uri' => '/redis/hset',
                'info' => '向hash缓存添加元素出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }

    /**
     * set 操作
     * @param $name
     * @param $value
     * 为$name 增加一个元素
     */
    public static function sadd($name,$value){
        if(!self::selectServer()) return false;
        try {
            if(!is_array($value)){
                $value = array($value);
            }
            return self::$handler->sadd($name, $value);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'uri' => '/redis/sadd',
                'info' => '向集合缓存添加元素出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }//end

    /**
     * set 操作
     * @param $name
     * @param $value
     * 为$name 删除一个元素 -- 出错 用不了
     */
    public static function srem($name,$value){
        if(!self::selectServer()) return false;
        try {
            return self::$handler->srem($name, $value);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'uri' => '/redis/srem',
                'info' => '向hash缓存删除元素出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }//end

    /**
     * @param $name
     * //smembers 返回当前表的所有元素  -- 出错 用不了
     */
    public static function smembers($name){
        if(!self::selectServer()) return false;
        try {
            return self::$handler->smembers($name);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'uri' => '/redis/smembers',
                'info' => '向hash缓存添加元素出错',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }

    /**
     * @param $name
     * @param $value
     * 判断 $value 是否属于 $name 列表中
     */
    public static function sismember($name,$value){
        if(!self::selectServer()) return false;
        try {
            return self::$handler->sismember($name,$value);
        }catch(\Exception $e){
            Applog::appLog('error',[
                'uri' => '/redis/sismember',
                'info' => '查询某个元素是否存在',
                'catch-e' => $e->getMessage(),
                'file' => __FILE__,
                'line' => $e->getLine(),
            ]);
            return false;
        }
    }

}
?>